﻿using LatteCoffee.coffeemake;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace LatteCoffee.coffeemodel
{
    public class IceMachine
    {
        private static IceMachine instance;
        private IceMachine() { }
        /// <summary>
        /// 串口实例
        /// </summary>
        SerialPort serialPort = new SerialPort();
        /// <summary>
        /// 接收数据
        /// </summary>
        private List<byte> buffer = new List<byte>();
        //是否发送文本
        bool sendText = false;
        /// <summary>
        /// 串口初始化
        /// </summary>
        public void InitIceMachine()
        {
            try
            {
                //注册串口接收到数据事件的回调函数
                serialPort.DataReceived += GetReceiveMsg;
            }
            catch (Exception ex)
            {
                return;
            }
        }
        /// <summary>
        /// 串口连接
        /// </summary>
        /// <param name="PortName">通讯端口</param>
        /// <param name="BaudRate">波特率</param>
        /// <param name="Parity_Sel">奇偶校验</param>
        /// <param name="DataBits">每个字节标准数据位长度</param>
        /// <param name="StopBits">停止位</param>
        public void IceMachineConnect(string PortName, int BaudRate, string Parity_Sel, int DataBits, double StopBits)
        {
            try
            {
                if (!serialPort.IsOpen)
                {
                    //设定参数PortName
                    serialPort.PortName = PortName;
                    serialPort.BaudRate = BaudRate;
                    serialPort.Parity = GetSelectedParity(Parity_Sel);
                    serialPort.DataBits = DataBits;
                    serialPort.StopBits = GetSelectedStopBits(StopBits);
                    serialPort.Encoding = Encoding.UTF8;

                    try
                    {
                        //打开串口
                        serialPort.Open();
                    }
                    catch (Exception)
                    {
                        //MessageBox.Show("无法打开此串口，请检查是否被占用");
                        return;
                    }
                }
                else
                {
                    if (serialPort != null)
                    {
                        //关闭串口
                        serialPort.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                return;
            }
        }
        /// <summary>
        /// 获取窗体选中的停止位
        /// </summary>
        /// <returns></returns>
        private StopBits GetSelectedStopBits(double StopBits_Sel)
        {
            switch (StopBits_Sel)
            {
                case 1:
                    return StopBits.One;
                case 1.5:
                    return StopBits.OnePointFive;
                case 2:
                    return StopBits.Two;
                default:
                    return StopBits.One;
            }
        }
        /// <summary>
        /// 获取窗体选中的奇偶校验
        /// </summary>
        /// <returns></returns>
        public Parity GetSelectedParity(string Paritysel)
        {
            switch (Paritysel)
            {
                case "Odd":
                    return Parity.Odd;
                case "Even":
                    return Parity.Even;
                case "Mark":
                    return Parity.Mark;
                case "Space":
                    return Parity.Space;
                case "None":
                default:
                    return Parity.None;
            }
        }
        /// <summary>
        /// 获取接收到的数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GetReceiveMsg(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                // var  ddd=serialPort.BytesToRead
                //读取串口缓冲区的字节数据
                byte[] result = new byte[serialPort.BytesToRead];
                serialPort.Read(result, 0, serialPort.BytesToRead);
                buffer.AddRange(result);
                string str = "";// $"{DateTime.Now}：\n";

                //判断读写模式
                //将接收到的字节数组转换为指定的消息格式
                if (sendText)
                {
                    if (buffer.Count > 0x03)
                        str += $"{Encoding.ASCII.GetString(result)}";
                    //if (str.Length > 16)
                    //    str = str.Substring(16, str.Length - 16);
                    for (int i = 0; i < result.Length; i++)
                    {
                        str += $"{result[i].ToString("X2")} ";
                    }
                    if (str.Length >= 42)
                        str = str.Substring(str.Length - 42, 42);

                }
                else
                {
                    for (int i = 0; i < result.Length; i++)
                    {
                        str += $"{result[i].ToString("X2")} ";
                    }
                }
                Thread.Sleep(1);
            }
            catch (Exception ex)
            {
                return;
            }
        }

    }
}
